//
//  BMWShareCollectionView.swift
//  BMWOpenShare
//
//  Created by Li Shengbing, (Shengbing.Li@partner.bmw.com) on 2019/6/5.
//  Copyright © 2019年 shanghai. All rights reserved.
//

import UIKit

class BMWShareCollectionView: UICollectionView {

    fileprivate let cellIdentifier = "cellIdentifier"
    fileprivate let showCount: Int = 8
    
    var dataSourceForArray: [BMWShareModel]? = nil {
        didSet {
            guard let _ =  dataSourceForArray else { return }
            self.reloadData()
        }
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        self.setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = self.bounds.size
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumLineSpacing = 0
        self.isPagingEnabled = true
    }
    
    fileprivate func setupUI() {
        self.delegate = self
        self.dataSource = self
        self.showsHorizontalScrollIndicator = false
        self.register(BMWShareCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
    }
}

extension BMWShareCollectionView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let datas =  dataSourceForArray else {
            return 0
        }
        return (datas.count - 1) / showCount + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! BMWShareCollectionViewCell
        self.setupCellDataWith(cell: cell, indexPath: indexPath)
        return cell
    }
    
    fileprivate func setupCellDataWith(cell: BMWShareCollectionViewCell, indexPath: IndexPath) {
        guard let datas = dataSourceForArray, datas.count >= 1 else { return }
        let starIndex = indexPath.item * showCount
        var endIndex = (indexPath.item + 1) * showCount - 1
        
        if endIndex > datas.count - 1 {
            endIndex = datas.count - 1
        }
        cell.configCellWithIndexPath(rowDatas: Array(datas[starIndex...endIndex]), indexPath: indexPath)
    }
}
